"use client";
import * as React from "react";
import { useState, useRef, useEffect } from "react";
import { ChevronDown, Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";

function CommonSelector({ onValueChange, name, placeholder, label, items, value, defaultValue="" }) {
  const [searchQuery, setSearchQuery] = useState("");
  const [isExpanded, setIsExpanded] = useState(false);
  const [selectedValue, setSelectedValue] = useState(value || defaultValue || "");
  const containerRef = useRef(null);
  const inputRef = useRef(null);

  // 过滤选项
  const filteredItems = items.filter((item) =>
    item.label.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // 找到选中的项目
  const selectedItem = items.find(item => item.value === selectedValue);

  // 处理选项点击
  const handleItemSelect = (selectedValue) => {
    setSelectedValue(selectedValue);
    setIsExpanded(false);
    setSearchQuery("");

    // 调用外部回调
    if (onValueChange) {
      onValueChange(selectedValue);
    }
  };

  // 处理输入框聚焦
  const handleInputFocus = () => {
    setIsExpanded(true);
  };

  // 处理箭头点击
  const handleArrowClick = (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (isExpanded) {
      setIsExpanded(false);
      setSearchQuery("");
      inputRef.current?.blur(); // 移除输入框焦点
    } else {
      setIsExpanded(true);
      inputRef.current?.focus(); // 聚焦到输入框
    }
  };

  // 处理点击外部关闭
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setIsExpanded(false);
        setSearchQuery("");
      }
    };

    if (isExpanded) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [isExpanded]);

  // 处理键盘事件
  const handleKeyDown = (e) => {
    if (e.key === 'Escape') {
      setIsExpanded(false);
      setSearchQuery("");
    }
  };

  return (
    <div ref={containerRef} className="relative w-full">
      {/* 隐藏的原生select，用于表单提交 */}
      <select
        name={name}
        value={selectedValue}
        onChange={() => {}} // 由上面的逻辑控制
        className="sr-only"
        tabIndex={-1}
      >
        <option value="">{placeholder || "请选择..."}</option>
        {items.map((item) => (
          <option key={item.value} value={item.value}>
            {item.label}
          </option>
        ))}
      </select>

      {/* 显示/搜索输入框 */}
      <div className="relative">
        <Input
          ref={inputRef}
          placeholder={!selectedItem ? (placeholder || "请选择...") : ""}
          value={isExpanded ? searchQuery : (selectedItem ? selectedItem.label : "")}
          onChange={(e) => setSearchQuery(e.target.value)}
          onFocus={handleInputFocus}
          onKeyDown={handleKeyDown}
          className={cn(
            "w-full pr-10 cursor-pointer",
            selectedItem ? "text-foreground" : "text-muted-foreground"
          )}
          autoComplete="off"
          autoCorrect="off"
          autoCapitalize="off"
        />

        {/* 下拉箭头 - 移除pointer-events-none，添加点击事件 */}
        <div
          className="absolute inset-y-0 right-0 flex items-center pr-3 cursor-pointer"
          onClick={handleArrowClick}
          onMouseDown={(e) => e.preventDefault()} // 防止影响输入框焦点
        >
          <ChevronDown
            className={cn(
              "h-4 w-4 text-gray-400 transition-transform duration-200",
              isExpanded && "transform rotate-180"
            )}
          />
        </div>
      </div>

      {/* 下拉选项列表 */}
      {isExpanded && (
        <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-md shadow-lg max-h-60 overflow-auto">
          {/* 搜索提示 */}
          {searchQuery && (
            <div className="px-3 py-2 text-xs text-gray-500 border-b bg-gray-50">
              <Search className="inline w-3 h-3 mr-1" />
              搜索: &quot;{searchQuery}&quot;
            </div>
          )}

          {/* 选项列表 */}
          <div className="py-1">
            {filteredItems.length > 0 ? (
              filteredItems.map((item) => (
                <div
                  key={item.value}
                  className={cn(
                    "px-3 py-2 text-sm cursor-pointer select-none transition-colors",
                    "hover:bg-gray-100 active:bg-gray-200",
                    selectedValue === item.value && "bg-blue-50 text-blue-600 font-medium"
                  )}
                  onMouseDown={(e) => {
                    // 防止触发input的blur事件
                    e.preventDefault();
                  }}
                  onClick={() => handleItemSelect(item.value)}
                  onTouchEnd={(e) => {
                    // 移动端触摸处理
                    e.preventDefault();
                    handleItemSelect(item.value);
                  }}
                >
                  <div className="flex items-center justify-between">
                    <span>{item.label}</span>
                    {selectedValue === item.value && (
                      <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
                    )}
                  </div>
                </div>
              ))
            ) : (
              <div className="px-3 py-2 text-sm text-gray-500 text-center">
                无匹配结果
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export default CommonSelector;